package main

import (
	"context"
	"fmt"
	"go-kit/grep_demo"
	"google.golang.org/grpc"
	"log"
	"net"
	"runtime"
	"time"
)

type demos struct {
}

func (*demos) Sum(ctx context.Context, req *grep_demo.SumRequest) (*grep_demo.SumReply, error) {
	return &grep_demo.SumReply{V: req.A + req.B, Err: ""}, nil
}

func main() {
	rpcserver()
	runtime.Gosched()
	rpcclient()
}

func rpcserver() {
	listener, err := net.Listen("tcp", ":8888")
	if err != nil {
		return
	}
	server := grpc.NewServer()
	dd := demos{}
	grep_demo.RegisterAddServer(server, &dd)
	go server.Serve(listener)
}

func rpcclient() {
	// 1. 创建一个连接
	conn, err := grpc.Dial(":8888", grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
		return
	}
	defer conn.Close()

	// 2. 然后创建客户端
	client := grep_demo.NewAddClient(conn)
	now := time.Now()
	for x := 0; x < 10000; x++ {
		func() {
			// 3. rpc调用
			ctx, cancel := context.WithTimeout(context.Background(), time.Second)
			defer cancel()
			response, err := client.Sum(ctx, &grep_demo.SumRequest{A: 1, B: 2})
			if err != nil {
				fmt.Printf("err=%s\n", err)
			} else {
				fmt.Printf("{\"result\":%d}\n", response.V)
			}
		}()
	}
	fmt.Println(time.Now().Sub(now).Milliseconds())
}
